const through2 = require('through2');
const util = require('gulp-util');
var PluginError = util.PluginError;
let PLUGIN_NAME = 'gulp-prefixer';

//through2 可以当做函数来执行？且返回一个 stream？
function prefixStream(prefixText){
    var stream = through2();
    stream.write(prefixText);
    return stream;
}

function gulpPrefixer(prefixText){
    if(!prefixText){
        throw new PluginError(PLUGIN_NAME, 'Missing prefix text!');
    }
    prefixText = new Buffer(prefixText);

    return through2.obj(function(file, enc, cb){
        //这个file 是什么对象，都附带了哪些方法？
        if(file.isNull()){
            cb(null, file);
        }

        if(file.isBuffer()){
            file.contents = Buffer.concat([prefixText, file.contents]);
        }

        if(file.isStream()){
            // 转为 stream
            file.contents = file.contents.pipe(prefixStream(prefixText)); 
        }

        cb(null, file);
    });
}